{- This file is part of funbot.
 -
 - Written in 2015 by fr33domlover <fr33domlover@rel4tion.org>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

{-# LANGUAGE OverloadedStrings #-}

module FunBot.Sources.WebListener.Gogs
    ( dispatchGogs
    )
where

import Data.Maybe (fromMaybe)
import FunBot.ExtEvents
import Network.HTTP (Request (..))

import qualified Data.Text as T
import qualified Web.Hook.Gogs as G

refToBranch :: T.Text -> T.Text
refToBranch ref = fromMaybe ref $ T.stripPrefix "refs/heads/" ref

nl c = c == '\n' || c == '\r'

makeCommit commit =
    let author = T.unpack $ G.userName $ G.commitAuthor commit
        msg    = T.unpack $ T.takeWhile (not . nl) $ G.commitMessage commit
        url    = T.unpack $ G.commitUrl commit
    in  Commit author msg url

makeBranch ref repo =
    let branch = T.unpack $ refToBranch ref
        repo'  = T.unpack $ G.repoName repo
        owner  = T.unpack $ G.userUsername $ G.repoOwner repo
    in  Branch branch repo' owner

fromGogs push =
    let commits = map makeCommit $ G.pushCommits push
        branch = makeBranch (G.pushRef push) (G.pushRepository push)
    in  GitPushEvent $ Push branch (reverse commits)

dispatchGogs push _pushMany request =
    case G.parse $ rqBody request of
        Left e -> do
            putStrLn $ "Web hook source: Gogs: " ++ show e ++ ":"
            print $ rqBody request
        Right pushInfo -> push $ fromGogs pushInfo
